package com.rxmvp.baselibrary.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.StringDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Set;

public class SpHelper {

    public static final String ACCESS_TOKEN = "accesstoken";
    public static final String OPEN_ID = "openid";

    private static SharedPreferences sp;
    private static SpHelper mSpHelper;

    //枚举
    @StringDef({ACCESS_TOKEN, OPEN_ID})
    @Retention(RetentionPolicy.SOURCE)
    public @interface SpKey{
    }

    public static void init(Context context){
        if (sp == null){
            sp = PreferenceManager.getDefaultSharedPreferences(context);
            mSpHelper = new SpHelper();
        }
    }

    public static SpHelper getInstance(){
        if (mSpHelper == null){
            throw new NullPointerException("init() method must be invoke firstly.");
        }
        return mSpHelper;
    }

    private SpHelper(){}

    public void putInt(@SpKey String key, int value) {
        sp.edit().putInt(key, value).apply();
    }

    public int getInt(@SpKey String key, int dValue) {
        return sp.getInt(key, dValue);
    }

    public void putLong(@SpKey String key, long value) {
        sp.edit().putLong(key, value).apply();
    }

    public long getLong(@SpKey String key, Long dValue) {
        return sp.getLong(key, dValue);
    }

    public void putFloat(@SpKey String key, float value) {
        sp.edit().putFloat(key, value).apply();
    }

    public Float getFloat(@SpKey String key, Float dValue) {
        return sp.getFloat(key, dValue);
    }

    public void putBoolean(@SpKey String key, boolean value) {
        sp.edit().putBoolean(key, value).apply();
    }

    public Boolean getBoolean(@SpKey String key, boolean dValue) {
        return sp.getBoolean(key, dValue);
    }

    public void putString(@SpKey String key, String value) {
        sp.edit().putString(key, value).apply();
    }

    public void putStringSet(@SpKey String key, Set<String> value) {
        sp.edit().putStringSet(key, value).apply();
    }

    public Set<String> getStringSet(@SpKey String key, Set<String> value) {
        return sp.getStringSet(key, value);
    }

    public String getString(@SpKey String key, String dValue) {
        return sp.getString(key, dValue);
    }

    public void remove(@SpKey String key) {
        if (isExist(key)) {
            SharedPreferences.Editor editor = sp.edit();
            editor.remove(key);
            editor.apply();
        }
    }

    public boolean isExist(@SpKey String key) {
        return sp.contains(key);
    }
}